#define THREAD_COUNT 10000
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

//回调函数
void *sum_func(void *arg)
{
    int *p = (int *)arg;
    // 加锁
    pthread_mutex_lock(&counter_mutex);
    *p+=1;
    // 解锁
    pthread_mutex_unlock(&counter_mutex);
    return NULL;
}

int main(int argc, char const *argv[])
{
    int sum=0;

    pthread_t tids[THREAD_COUNT];
    //循环多次累加
    for (int i = 0; i < THREAD_COUNT; i++)
    {
         pthread_create(&tids[i], NULL, sum_func, &sum);
    }
    
    //等待所有线程结束
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_join(tids[i], NULL);
    }
    //打印结果
    printf("sum=%d\n", sum);

    pthread_mutex_destroy(&counter_mutex);

    return 0;
}
